<?php

/*
  Project: Blogmer - Open Source Blogging Software
  Type: PHP and database
  Desc: Contains all functions related to categories.
  Author: Yashpal
  Usage:  	$this->load->model('Users_model','',TRUE);	-Load model
			$this->Users_model->UserRegistration();  	- Insert value in database
			$this->Users_model->ForgetPassword();    	- Generate reset password url
			$this->Users_model->ResetPassword();     	- Generate new password
			self::_randomstrings(number) 				- Local use only
			

  Function name : 
  UserRegistration       -> This function will insert user detail in database.
  ForgetPassword()       -> This function takes email as input and generate an reset password url.  
  ResetPassword()		 -> This function will reset the password and generate a new password.	
  _randomstrings($number) -> This function will create random alphanumeric given number of string.
  
  MemberGroups

      Admin                              5
      Author/Contributer                 34
      Member                             69
      Guest                              106
      Ban                                124

*/

class Users_model extends Model {

    function Users_model()
    {
        // Call the Model constructor
        parent::Model();
    }
	
	//Function Name - _randomstrings
	//This function generate random alphanumeric string
	//Parram - Number of characters
	//output - Give an random string of given number
		
	static function _randomstrings($number){
	
	//Generate fixed number of random characters
			
			$numofletters = $number;
			$vercode="";
			$literki = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W','1','2','3','4','5','6','7','8','9');
			$ilosc_literek = count($literki);
			for ($licz = 0; $licz < $numofletters; $licz++) 
			{
				$rand = rand(0, $ilosc_literek-1);
				$vercode = $vercode.$literki[$rand];
			}
			// $vercode;   - Use this random input number of digits string 
			
   		 return $vercode;
	  }

  
	function _CallSettings()
	{
		$query = $this->db->get('advancedsettings');
		$advancedsettings = $query->row_array();
			
		$query = $this->db->get('generalsettings');
		$generalsettings = $query->row_array();
		
		$settings=array_merge($advancedsettings,$generalsettings);
		return $settings;
	}
	//Function Name - ForgetPassword
	//This function takes email as input and generate an reset password url
	//Parram - Number of characters
	//output - Send mail to user containing password info
	
	
 	function ForgetPassword()
	{
		
		//getting random alphanumeric characters
		$vercode=self::_randomstrings(10);
		
		$email=$this->input->post('email');
		$epass=dohash($vercode);
		$settings=self::_CallSettings();
			
		$this->db->where('MEmail',$email);
		$query =$this->db->get('users');
		$single_row=$query->row_array();
		
		if ($query->num_rows() > 0)
		{
			//foreach ($query->result() as $row)
			//{   $id=$row->MemberID;		}		
			$id=$single_row['MemberID'];
		
			$sendurl=base_url()."users/ResetPassword/".$id."/".$vercode;	
			
			$data = array('CheckCode'=>$vercode);
			$this->db->where('MemberID',$id);
			$this->db->update('users', $data);
			$str1=$this->db->affected_rows();
				
			if($str1)
			{
						
				if($settings['SendMailToNewUsers']==1)
				{
					$this->load->library('email');
					$this->email->from("info@".$settings['BLOGName'], $settings['BLOGName']);
					$this->email->to($this->input->post('email'));
					$this->email->subject('Registration -'.$settings['BLOGName']);
					$this->email->message('Thank you for registration.');
					
					$checkemail=$this->email->send();
					
					if ( $checkemail)
					{
						    // No error Email is sent successfully
							$msg="Mail has been sent.Check your mail and reset the password.";
					}
					else
					{	/*	Error Most common reason -Failed to connect to mailserver 
						at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()*/
							$msg="Sending email failed.Contact Webmaster.";	
					}
					
					//$msg="Mail has been sent.Check your mail and reset the password.";
					
				}
				else
				{
					$msg="Click on above link <a href=\"$sendurl\" title=\"Reset Password\" >Reset Password</a>";
				}
			}
			else
			{
				$msg="Error: Try again";
			}
					
		}	
		else
		{	
			$msg= "<p>No Email found.Try again.</p><p><a href='JavaScript:history.go(-1)'>Return to Previous Page</a></p>
";
		}						
			
				
				$data['message']=$msg;
				$data['time']=50000;
				$data['title']="Information Page";
				$data['header']="Information";
				$data['url']="/users/ForgetPassword";

			
			 $this->load->view('info',$data);
		
	}
	
	//Function Name - ResetPassword
	//This function will reset the password and generate a new password.
	//Parram - no input
	//output - Send mail to user containing URL for reseting password.
	
	function ResetPassword()
	{
		$id=$this->uri->segment(3);
		$checkcode=$this->uri->segment(4);
		
		if($checkcode=="")
		{$checkcode="54DSW4";}
		//getting random alphanumeric characters
		$vercode=self::_randomstrings(8);
		$settings=self::_CallSettings();
		//$email=$this->input->post('email');
		$epass=dohash($vercode);
		$emsg="Your new Password -> <strong>$vercode</strong>";
			
		$data = array('MPassword' => $epass,'CheckCode'=>"");
	 	$this->db->where(array('MemberID'=>$id,'CheckCode'=>$checkcode));
		$this->db->update('users', $data);
		$str1=$this->db->affected_rows();
		
		
		//$CI =& get_instance();
		//$CI->load->model('Settings_model','',TRUE);
		//$blogsetting=$CI->Settings_model->Blog_Settings();
		
		if($settings['SendMailToNewUsers']==1)
		{	$msg="New Password is set.Check Your mail.";		}
		else
		{	$msg=$emsg;						}
								
			 if($str1)
				$msg= "New Password is set.<br>".$msg;
			 else
				$msg= "<div class=\"error\">No Valid Code/ID found.Try again.</div>";
			
				
				$data['time']=50000;
				$data['message']=$msg;
				$data['title']="Information Page";
				$data['header']="Information";
				$data['url']="/users/ForgetPassword";

			
			 $this->load->view('info',$data);
		
	}
	
	function ActivateUser()
	{
		$id=$this->uri->segment(3);
		$checkcode=$this->uri->segment(4);
		
		if($checkcode=="")
		{$checkcode="54DSW4";}
		
		$settings=self::_CallSettings();
		//$email=$this->input->post('email');
		
			
		$data = array('Activate' => 1,'CheckCode'=>"");
	 	$this->db->where(array('MemberID'=>$id,'CheckCode'=>$checkcode));
		$this->db->update('users', $data);
		$str1=$this->db->affected_rows();
		
			
		if($settings['SendMailToNewUsers']==1)
		{	$data['time']=2;$msg="Activation successfully done";		}
		else
		{	$data['time']=50000;$msg="Activation Failed";						}
								
			 if($str1)
				$msg= "Account has beed activated.Now you can login";
			 else
				$msg= "<div class=\"error\">No Valid Code/ID found.Try again.</div>";
			
				
				
				$data['message']=$msg;
				$data['title']="Information Page";
				$data['header']="Information";
				$data['url']="users/login";

			
			 $this->load->view('info',$data);
		
	}
	//Function Name - UserRegistration
	//This function submit  registration information into database
	//Parram - no input
	//output - Info about registration
	
	function UserRegistration()
	{
		 	
			
			//getting random alphanumeric characters
			$vercode=self::_randomstrings(10); //Use this random 10 digit string as checkcode
			
			$settings=self::_CallSettings();
      	
			//checking whether email activation is required or not
			//by default yes
			 if($settings['SendMailToNewUsers']==1)
			 {
				 $activate=0;
				 $checkcode=$vercode;
			 }
			 else
			 {
				 $name=$this->input->post('firstname')." ". $this->input->post('lastname');
				 $activate=1;
				 $checkcode="";
			 }
			 
	 		/*		 
	 		user group code - 69   
			dohash - by default is sha algo 		default user role															*/
			//switch case to find proper value
			switch($settings['NewUserDefaultRole'])
			{
				case 69: $userrole=dohash(69);break; //member
				case 34: $userrole=dohash(34);break; //author/contributer
				case 5:  $userrole=dohash(5);break; //admin
				default: $userrole=dohash(69);break;  //member
			}
			            
			 
			 $insert = array(
                'MemberID' => '',
				'MName' => $this->input->post('username'),
				'MPassword' => dohash($this->input->post('password')),
				'MUrl' => $this->input->post('murl'),
                'MEmail' => $this->input->post('email'),
                'MFirstName' => $this->input->post('firstname'),
				'MLastName' => $this->input->post('lastname'),
				'MGroup' => $userrole,
				'MRegDate' =>date('Y-m-d H:i:s'),
				'Activate' => $activate ,
				'CheckCode' =>$checkcode 		
                
                );
            $check=$this->db->insert('users', $insert);
			
			$this->db->order_by('MemberID','DESC');
			$this->db->limit(1);
			$query=$this->db->get('users');
			$user=$query->row_array();
			$user_id=$user['MemberID'];
			
			//echo $user_id;
			
			
			if($check)
			{
				
				// check for registration EMail
				if( $settings['SendMailToNewUsers']==1)
				{
				
					$this->load->library('email');
					$config['mailtype'] = 'html';
					$this->email->initialize($config);

					$this->email->from("info@".$settings['BLOGName'], $settings['BLOGName']);
					$this->email->to($this->input->post('email'));
					$this->email->subject('Registration -'.$settings['BLOGName']);
					$this->email->message('<p>You need to activate your account.Click on link to activate.</p><p>'.anchor('users/ActivateUser/'.$user_id.'/'.$checkcode,'Activate Account').'</p><p>Thank you for registration.');
					
					$checkemail=$this->email->send();
					
					if ( $checkemail)
					{
						    // No error Email is sent successfully
							$emailmessage="Check your mail for confirmation";
					}
					else
					{	/*	Error Most common reason -Failed to connect to mailserver 
						at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()*/
							$emailmessage="Sending email failed.Contact Webmaster.";	
					}
				}
				else
				{
					$emailmessage="<p>Welcome $name, You can login.</p>";
				}
				
				//User successfully registered and message generated.
				$info['message']="<p>You are successfully registered.<p>".$emailmessage;
				
		  }
		  else
		  {
					//User Registration failed due to unknown error.
					//Most common error is wrong database settings.
					$info['message']="Unexpected Error...Registration Failed.";
					
		  }
		  
		  	$info['title']="Information Page";
			$info['header']="Information";
			$info['url']="/users/Login";
			$info['time']="3";
			
		  	$this->load->view('info',$info);
				
            
      }
	 
	  //????????????????????????????????????????????????
	  //switch case for other membergroup is remaining....
	  //?????????????????????????????????????????????????
	  
	  function ViewProfile($id)
	  {
		  	$this->db->where('MemberID',$id);
			$query=$this->db->get('users');
			
			if($query->num_rows()<=0)
			{
				return "Member ID not found";
			}
			
			$right_arr=$query->row_array();
			$left_arr=array('ID','Name','Password','Url','Email','First Name','Last Name','Member Group','Registration Date');
			array_pop($right_arr);
			array_pop($right_arr);
			if($right_arr['MGroup']=="a72b20062ec2c47ab2ceb97ac1bee818f8b6c6cb")
				$right_arr['MGroup']="Member";
			else
				$right_arr['MGroup']="Some Group";	
			$right_arr['MPassword']="<i>Hidden</i>";
			$right_arr['MEmail']="<i>Hidden</i>";
			
			$right_arr['MRegDate']= date("l, F jS, Y \\a\\t n:i A",strtotime($right_arr['MRegDate']));	
			//$list = array_combine($left_arr,$right_arr);
			//$list = $this->table->make_columns($row_arr, 2);
			//print_r($right_arr);
			//$this->table->add_row();
			
			$blah = array_combine($left_arr, $right_arr);
			
			$tmpl = array ('table_open'=> 
			'<div id="outer-collection">
			<table width="100%" cellspacing="2" cellpadding="2" border="0" >
			<thead>
				<tr>
					<th colspan="2">Member Profile</th>
				</tr>
			</thead>	
			<tfoot>
				<tr>
					<td>&nbsp;</td>

					<td >&nbsp;</td>
				</tr>
			</tfoot>
			<tbody>',

                    'heading_row_start'   => '<tr>',
                    'heading_row_end'     => '</tr>',
                    'heading_cell_start'  => '<th>',
                    'heading_cell_end'    => '</th>',

                    'row_start'           => '<tr>',
                    'row_end'             => '</tr>',
                    'cell_start'          => '<td>',
                    'cell_end'            => '</td>',

                    'row_alt_start'       => '<tr>',
                    'row_alt_end'         => '</tr>',
                    'cell_alt_start'      => '<td>',
                    'cell_alt_end'        => '</td>',

                    'table_close'         => '</tbody></table></div>'
              );

			$this->table->set_template($tmpl); 

			foreach($blah as $k=>$v)
			{ 
				$this->table->add_row($k,$v); 
			}
			return $this->table->generate(); 
			

			
	  }
	  
	  
	/*********************************************************************************/
	/**********************   Admin Functions  ***************************************/
	/*********************************************************************************/
	
	function DeleteUser($userid,$pageid)
	{
    $pageid=self::_RefinePagNav($pageid);
		$this->db->where('MemberID', $userid);
		$query=$this->db->delete('users');
		redirect('/admin/Manageusers/'.$pageid, 'refresh');
	}
	
	function activate_user($user_id,$page_id)
	{
		$data = array(
					   'Activate' => 1,
					   'CheckCode' => ""
					);
		$this->db->where('MemberID', $user_id);
		$this->db->update('users', $data); 
		
		$page_id=self::_RefinePagNav($page_id);
		redirect('/admin/Manageusers/'.$page_id, 'refresh');
	}
	
	function deactivate_user($user_id,$page_id)
	{

		$data = array( 'Activate' => 0);
		$this->db->where('MemberID', $user_id);
		$this->db->update('users', $data); 
		$page_id=self::_RefinePagNav($page_id);		
		redirect('/admin/Manageusers/'.$page_id, 'refresh');
	}
	
	 //Function Name - AddUser
	//This function register a new user
	//Parram - no input
	//output - Info about registration
	
	function edit_user($user_id,$page_id)
	{
		 	
		/*	dohash - by default is sha algo 		
		    default user role*/
		//switch case to find proper value
			switch($this->input->post('MemberGroup'))
			{
				case 69:  $userrole=dohash(69);	break; //member
				case 34: $userrole=dohash(34);	break; //author/contributer
				case 5:  $userrole=dohash(5);	break; //admin
			}
			if(trim($this->input->post('password'))=="")
			{ 
						$update = array(
                			'MName' => $this->input->post('username'),
							'MUrl' => $this->input->post('murl'),
							'MEmail' => $this->input->post('email'),
							'MFirstName' => $this->input->post('firstname'),
							'MLastName' => $this->input->post('lastname'),
							'MGroup' => $userrole,
						   );
			
			}
			else
			{
						 $update = array(
                			'MName' => $this->input->post('username'),
							'MUrl' => $this->input->post('murl'),
							'MPassword'=>dohash($this->input->post('password')),
							'MEmail' => $this->input->post('email'),
							'MFirstName' => $this->input->post('firstname'),
							'MLastName' => $this->input->post('lastname'),
							'MGroup' => $userrole,
						   );
			
			}
			            
			 

				$this->db->where(array('MemberID'=>$user_id));
	            $check=$this->db->update('users', $update);
			
				if($check)
				{
					   //User successfully registered and message generated.
					   $info['message']="<p>User successfully updated.<p>";
				}
				else
				{
						//User Registration failed due to unknown error.
						//Most common error is wrong database settings.
						$info['message']="Unexpected Error...Updation Failed.";
						
				}
		  
				$info['title']="Information Page";
				$info['header']="Information";
				$info['url']="/admin/EditUser/".$user_id;
				$info['time']="2";
				
				$this->load->view('info',$info);
				
            
      }
	  
	//Function Name - AddUser
	//This function register a new user
	//Parram - no input
	//output - Info about registration
	
	function create_user()
	{
		 	
		/*	dohash - by default is sha algo 		
		    default user role*/
		//switch case to find proper value
			switch($this->input->post('membergroup'))
			{
				case 69:  $userrole=dohash(69);	break; //member
				case 34: $userrole=dohash(34);	break; //author/contributer
				case 5:  $userrole=dohash(5);	break; //admin
			}
			            
			 
			 $insert = array(
                'MemberID' => '',
				'MName' => $this->input->post('username'),
				'MPassword' => dohash($this->input->post('password')),
				'MUrl' => $this->input->post('murl'),
                'MEmail' => $this->input->post('email'),
                'MFirstName' => $this->input->post('firstname'),
				'MLastName' => $this->input->post('lastname'),
				'MGroup' => $userrole,
				'MRegDate' =>date('Y-m-d H:i:s'),
				'Activate' => 1 ,
				'CheckCode' =>"" 		
                
                );
            $check=$this->db->insert('users', $insert);
			
			if($check)
			{
				   //User successfully registered and message generated.
				   $info['message']="<p>User successfully registered.<p>";
		    }
		    else
		    {
					//User Registration failed due to unknown error.
					//Most common error is wrong database settings.
					$info['message']="Unexpected Error...Registration Failed.";
					
		    }
		  
		  	$info['title']="Information Page";
			$info['header']="Information";
			$info['url']="/admin/Manageusers";
			$info['time']="2";
			
		  	$this->load->view('info',$info);
				
            
      }
	
 	function list_users($pageid)
	{
		$pageid=self::_RefinePagNav($pageid);
		
    $this->db->from('users');
	 	$cnt=$this->db->count_all_results();
		
		$config['base_url'] = site_url().'/admin/Manageusers/';
		$config['total_rows'] =$cnt;
		$config['per_page'] = '10';
		$config['num_links'] = '3';
		$config['uri_segment'] = '3';


		$this->pagination->initialize($config); 
		$this->db->order_by("MRegDate", "desc"); 
		$query = $this->db->get('users',$config['per_page'],$this->uri->segment(3));
		
		$out= "<table width=\"100%\" border=\"0\">";
		$out.="<caption>Members List</caption>
			<thead>
				<tr>
					<th scope=\"col\">Registration Date</th>
					<th scope=\"col\">Member Name</th>
					<th scope=\"col\">Activate</th>
					<th scope=\"col\">Profile</th>
					<th scope=\"col\">Edit</th>
					<th scope=\"col\">Delete</th>
				</tr>
			</thead>	
			<tfoot>
				<tr>
					<th scope=\"row\">Total</th>

					<td colspan=\"5\">$cnt Members</td>
				</tr>
			</tfoot>
			<tbody>";

		foreach ($query->result() as $row)
		{
			$out.=
			 "<tr>
			    <td><abbr title=\"$row->MRegDate\">".substr($row->MRegDate,0,10)."</abbr></td>
			    <td>".$row->MName."</td>
			    <td>";
						if($row->Activate)
							{ $out.=anchor('admin/DeactivateUser/'.$row->MemberID.'/'.$pageid,'Deactivate');}
						else
							{ $out.=anchor('admin/ActivateUser/'.$row->MemberID.'/'.$pageid,'Activate');}	
						
				$out.="</td>
				<td>".anchor('users/ViewProfile/'.$row->MemberID,'View')."</td>
			    <td>".anchor('admin/EditUser/'.$row->MemberID,'Edit')."</td>
			    <td>".anchor('admin/DeleteUser/'.$row->MemberID.'/'.$pageid,'Delete')."</td>
			  </tr>";
			
			
		} 
		$out.= "</tbody></table>";
		$out.= $this->pagination->create_links();
		return $out;
		
	}
	
	function _RefinePagNav($page_id)
	{
				if($page_id==1)
				$page_id=0;
				
				return $page_id;
	}	
	
	    

}

